﻿using FeedingReport.ViewModels;
using hyjx.bind;
using Microsoft.Win32;
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;

namespace FeedingReport.Commands
{
    public class ExportCommand : CommandBase
    {
        public override bool CanExecute(object? parameter)
        {
            if(parameter is not ReportPageViewModel vm)
                return false;

            if(vm.Reports.Count == 0) return false;

            return true;
        }

        public async override void Execute(object? parameter)
        {
            if (!CanExecute(parameter)) return;
            if (parameter is not ReportPageViewModel vm)
                return;

            if (vm.Reports.Count == 0)
            {
                MessageBox.Show("当前没有查询结果，无法导出。", "错误", MessageBoxButton.OK, MessageBoxImage.Error);
                return;
            }

            // 弹出文件保存窗口
            SaveFileDialog saveFileDialog = new()
            {
                Filter = "文本文件|*.csv",
                InitialDirectory = "D:\\", //设置初始目录

                FileName = $"{vm.Filter.SelectedMixerName.Value}_{vm.Filter.StartDate?.Year}_{vm.Filter.StartDate?.Month:D2}_{vm.Filter.StartDate?.Day:D2}.csv"
            };

            bool? showResult = saveFileDialog.ShowDialog();
            if (showResult == null || showResult.Value == false)
                return;

            try
            {
                //if (File.Exists(saveFileDialog.FileName))
                //    File.Delete(saveFileDialog.FileName);

                int total = 0; // 导出总行数

                vm.IsExporting = Visibility.Visible;

                await Task.Run(() =>
                {
                    // 获取要导出的数据
                    var query = vm.GetAllReports();
                    if (query == null)
                    {
                        MessageBox.Show("获取导出数据出错，导出失败。", "错误", MessageBoxButton.OK, MessageBoxImage.Error);
                        return;
                    }

                    total = query.Count();
                    if (total == 0)
                    {
                        MessageBox.Show("获取导出数据出错，导出失败。", "错误", MessageBoxButton.OK, MessageBoxImage.Error);
                        return;
                    }

                    hyjx.file.CsvHelper csv = new(saveFileDialog.FileName);
                    csv.AppendRow(new string[] { "类别", "开始时间", "结束时间", "设定值", "测量值" });

                    foreach (var data in query)
                    {
                        string materialCode = vm.GetMaterialName(data.MaterialCode);
                        if (string.IsNullOrEmpty(materialCode))
                            continue;
                        csv.AppendRow(new string[] { materialCode, 
                            data.StartTime != null ? data.StartTime.Value.ToString() : string.Empty,
                            data.EndTime != null ? data.EndTime.Value.ToString() : string.Empty,
                            data.SettingValue != null ? data.SettingValue.Value.ToString() : string.Empty,
                            data.ActualValue != null ? data.ActualValue.Value.ToString() : string.Empty});

                    }
                    csv.Dispose();

                    MessageBox.Show($"成功导出 {total} 条数据记录", "提示", MessageBoxButton.OK, MessageBoxImage.Information);
                });

            }
            catch (Exception ex)
            {
                string error = $"出现异常，导出失败：{ex.Message}";
                MessageBox.Show(error, "错误", MessageBoxButton.OK, MessageBoxImage.Error);
            }
            finally
            {
                vm.IsExporting = Visibility.Collapsed;
            }
        }
    }
}
